<script setup>

import {
  ArrowDown,
  Avatar,
  Document,
  EditPen, Expand,
  RemoveFilled,

} from "@element-plus/icons-vue";
import {nextTick, onMounted, provide} from "vue";
import {ref} from "vue";
import {doGet, doPost, doPut} from "@/util/request";
import {TOKEN_NAME} from "@/util/constants";
import {showMessage} from "@/util/message";
import {useRoute} from "vue-router";

//创建路由对象
const route = useRoute()

//计算激活的菜单路径
let activePath = ref('')
const computeActivePath = () => {
  let templatePath = route.path  // 获取当前路由路径
  // 将路由路径通过 / 进行分隔
  let pathArr = templatePath.split('/')   // /dashboard/user/add    ----》 ['','dashboard','user','add']
  // 判断
  if (pathArr.length > 3) {
    activePath.value = "/" + pathArr[1] + "/" + pathArr[2];
  } else {
    activePath.value = route.path
  }
}


onMounted(() => {
  //查询登录用户信息
  loadLoginUserInfo()
  // 激活菜单路径
  computeActivePath()
})
//登录用户对象信息
const loginUserInfo = ref({})
// 加载登录用户信息
const loadLoginUserInfo = () => {
  doGet('/api/user/login/info').then(resp => {
    if (resp.data.code === 200) {
      loginUserInfo.value = resp.data.data
    } else {
      //提示信息
      showMessage('查询用户失败', resp.data.msg, 'error')
    }
  })
}
//用户退出
const logout = () => {

  //发送请求
  doPost('/api/logout').then(resp => {
    if (resp.data.code === 200) {
      //清除token
      sessionStorage.removeItem(TOKEN_NAME)
      localStorage.removeItem(TOKEN_NAME)
      //提示信息
      showMessage('提示', 'success', '退出成功')
      //跳转到登录页面
      window.location.href = '/'
    } else {
      //提示信息
      showMessage('提示', 'error', '退出失败')
    }
  })
}

/*-------------用户个人信息-----------------*/
const dialogVisible = ref(false)
const logInfo = ref({})
//查询用户信息内容
const showUserInfo = () => {
  //显示对话框
  dialogVisible.value = true
  // 发送请求
  doGet('/api/user/detail', {}).then(resp => {
    if (resp.data.code === 200) {
      logInfo.value = resp.data.data
    } else {
      showMessage('查询用户信息失败', resp.data.msg, 'error')
    }
  })
}
/*-------------修改密码-----------------*/
//控制弹出框的model
const pwdFormRef = ref(false)
//修改表单对象的model
const pwdRuleForm = ref({})
//修改密码用户表单对象
const ruleFormRef = ref({})

//校验旧密码是否正确
const checkOldPassword = (rule, value, callback) => {
  //发送请求
  doGet('/api/user/checkOldPwd', {
    oldPwd: value
  }).then(resp => {
    if (resp.data.code === 200) {
      callback()
    } else {
      callback(new Error(resp.data.msg))
    }
  })
}
//验证新密码是否与老密码一致
const checkNewPassword = (rule, value, callback) => {
  if (value !== pwdRuleForm.value.oldPwd) {
    callback()
  } else {
    callback(new Error('新密码不能与旧密码一致'))
  }
}
//验证两次新密码是否一致
const checkConfirmPassword = (rule, value, callback) => {
  if (value !== pwdRuleForm.value.newPwd) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 修改密码规则对象
const rules = {
  oldPwd: [
    {required: true, message: '请输入旧密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'},
    {validator: checkOldPassword, trigger: 'blur'}
  ],
  newPwd: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'},
    {validator: checkNewPassword, trigger: 'blur'}
  ],
  confirmPwd: [
    {required: true, message: '请再次输入新密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'},
    {validator: checkConfirmPassword, trigger: 'blur'}
  ]
}
//提交修改密码
const submitForm = () => {
  //发送请求
  doPut('/api/user/updatePwd', {loginPwd: pwdRuleForm.value.newPwd}).then(resp => {
    if (resp.data.code === 200) {
      //提示信息
      showMessage('修改密码成功', 'success')
      //清空token
      sessionStorage.removeItem(TOKEN_NAME)
      localStorage.removeItem(TOKEN_NAME)
      //重新登录
      window.location.href = '/'
    } else {
      //提示信息
      showMessage('修改密码失败', 'error')
    }
  })
}
//控制右侧中间体刷新页面
let refresh = ref(true)
//刷新页面
const refreshPage = () => {
  refresh.value = false
  nextTick(() => {
    refresh.value = true
  })
}
//设置子页面使用
provide('refresh', refreshPage)

//重置表单按钮
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}


const isCollapse = ref()
const drawer = ref(false)


</script>

<template>
  <el-container>


    <el-drawer v-model="drawer"
               direction="ltr"
               :modal="true"
               title="系统菜单"
               :size="'240px'"
               :close-delay="0"
               :open-delay="0"
               :close-on-click-modal="true"
               :with-header="true">
      <el-menu
          :router="true"
          unique-opened
          class="el-menu-vertical-demo"
          :default-active="activePath"
          :collapse="isCollapse"
          style="border-right: 0 solid var(--el-menu-border-color)">
        <el-sub-menu :index="index" v-for="(menu, index) in loginUserInfo.menus">
          <template #title>
            <el-icon>
              <component :is="menu.icon"/>
            </el-icon>
            <span>
              <font size="3px">
                {{ menu.name }}
              </font>
          </span>
          </template>
          <el-menu-item :index="chidMenus.url" v-for="chidMenus in menu.menusPermission" @click="drawer = false">
            <template #title>
              <el-icon>
                <component :is="chidMenus.icon"/>
              </el-icon>
              {{ chidMenus.name }}
            </template>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-drawer>

    <el-container>
      <!--右侧头部-->
      <el-header>
        <el-icon color="#fff" size="25px" style="margin-top:6px">
          <Expand @click="drawer = true"/>
        </el-icon>
        <span style="color: #f0f2f5;margin-left: 770px" align-top="2px">
          <font size="6px" style="font-family: 华文行楷,sans-serif">
            动力云客管理系统
          </font>
        </span>

        <el-dropdown class="el-dropdown-link">
          <span>
            <el-icon><Avatar/></el-icon>
            {{ loginUserInfo.name }}
            <el-icon class="el-icon--right">
              <arrow-down/>
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>

              <el-dropdown-item @click="showUserInfo">
                <el-icon>
                  <Document/>
                </el-icon>
                个人信息
              </el-dropdown-item>

              <el-dropdown-item @click="pwdFormRef=true">
                <el-icon>
                  <EditPen/>
                </el-icon>
                修改密码
              </el-dropdown-item>

              <el-dropdown-item @click="logout">
                <el-icon>
                  <RemoveFilled/>
                </el-icon>
                退出登录
              </el-dropdown-item>

            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>

      <!--右侧中部-->
      <el-main>
        <router-view v-if="refresh"/>
      </el-main>

      <!--右侧下部-->
      <el-footer>
        @版权所有 2025 - 2099 动力云客管理系统 || 联系方式：12345678901 || 邮箱：12345678901@qq.com
        <br>
        <a href="https://beian.miit.gov.cn/">京ICP备2025000000号-1</a>

      </el-footer>
    </el-container>
  </el-container>

  <!--用户个人信息弹出框-->
  <el-dialog
      v-model="dialogVisible"
      width="500"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :align-center="true"
      :center="true"
      :show-close="false"
      title="个人信息">

    <el-form :model="logInfo">
      <el-form-item label="账号: ">
        {{ logInfo.loginAct }}
      </el-form-item>

      <el-form-item label="姓名: ">
        {{ logInfo.name }}
      </el-form-item>

      <el-form-item label="电话: ">
        {{ logInfo.phone }}
      </el-form-item>

      <el-form-item label="邮箱: ">
        {{ logInfo.email }}
      </el-form-item>

      <el-form-item label="创建人: ">
        {{ logInfo.createBy }}
      </el-form-item>

      <el-form-item label="创建时间: ">
        {{ logInfo.createTime }}
      </el-form-item>

      <el-form-item label="编辑人: ">
        {{ logInfo.editByName }}
      </el-form-item>

      <el-form-item label="编辑时间: ">
        {{ logInfo.editTime }}
      </el-form-item>

      <el-form-item label="最近登录时间: ">
        {{ logInfo.lastLoginTime }}
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--用户修改密码弹出框-->
  <el-dialog
      v-model="pwdFormRef"
      width="500"
      align-center
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :show-close="false"
      title="修改密码">

    <el-form
        ref="ruleFormRef"
        :model="pwdRuleForm"
        :rules="rules">
      <el-form-item label="原密码:&nbsp;&nbsp;&nbsp;" prop="oldPwd">
        <el-input v-model="pwdRuleForm.oldPwd" placeholder="请输入原密码" show-password></el-input>
      </el-form-item>

      <el-form-item label="新密码:&nbsp;&nbsp;&nbsp;" prop="newPwd">
        <el-input v-model="pwdRuleForm.newPwd" placeholder="请输入新密码" show-password></el-input>
      </el-form-item>

      <el-form-item label="确认密码:" prop="confirmPwd">
        <el-input v-model="pwdRuleForm.confirmPwd" placeholder="请输入确认密码" show-password></el-input>
      </el-form-item>
      <div class="dialog-footer">
        <el-button @click="resetForm(ruleFormRef);pwdFormRef = false">关闭</el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">重置</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
      </div>
    </el-form>
  </el-dialog>

</template>

<style scoped>
.menu-title {
  color: black;
  font-family: '华文细黑', serif;
  font-size: 26px;
}

::v-deep(.el-overlay) {
  background-color: rgba(0, 0, 0, 0.001); /* 设置背景颜色和透明度 */
}

.menu-header {
  color: #fff;
  text-align: center;
  line-height: 24px;
}


.el-container {
  height: calc(98.3vh);
}

.el-menu-item{
  font-family: '华文楷体', serif;
  font-size: 16px;
}
.el-sub-menu {
  font-family: '华文楷体', serif;
}

.dialog-footer {
  text-align: right;
}

.el-form-item {
  margin-left: 60px;
}

.el-dropdown {
  float: right;
  margin-top: 10px;
  margin-right: 30px;
  cursor: pointer;
  font-weight: bolder;
  color: #fff;
  font-family: '新宋体', serif;
  display: flex;
  align-items: center;
  border: none;
  outline: unset;
}

.el-dropdown :deep(.el-tooltip__trigger:focus-visible) {
  outline: unset;
}

.el-header {
  background-color: #545c64;
  color: #333;
  height: 40px;
}

.el-footer {
  height: 60px;
  font-weight: bolder;
  text-align: center;
  font-size: 15px;
  font-family: "华文楷体", serif;
}


.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}


</style>
